package com.zmx.patients.view.activity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.google.gson.Gson;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.Patient;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;
import com.zmx.patients.view.util.TimeCount;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 时间：2020/5/3 21:32
 * 功能：添加患者
 */
public class AddPatientActivity extends BaseActivity {

    @BindView(R.id.button_jian)
    Button buttonJian;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.button_jin)
    Button buttonJin;
    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.guomin_a)
    Button guominA;
    @BindView(R.id.guomin_b)
    Button guominB;
    @BindView(R.id.bingshi_a)
    Button bingshiA;
    @BindView(R.id.bingshi_b)
    Button bingshiB;
    @BindView(R.id.guomin)
    EditText guomin;
    @BindView(R.id.bingshi)
    EditText bingshi;
    @BindView(R.id.weight)
    EditText weight;
    @BindView(R.id.reg_account)
    EditText regAccount;
    @BindView(R.id.reg_code_edt)
    EditText regCodeEdt;
    @BindView(R.id.reg_code_button)
    TextView regCodeButton;
    @BindView(R.id.text_bd)
    TextView text_bd;
    @BindView(R.id.registered_button)
    Button registered_button;
    @BindView(R.id.numbers)
    EditText numbers;
    @BindView(R.id.reg_layout)
    LinearLayout reg_layout;
    @BindView(R.id.mes_layout)
    LinearLayout mes_layout;

    private String phone_number;//手机号码

    private int sex = 0;

    private Boolean bs = false;
    private Boolean gm = false;

    private String relation;

    private Patient patient;

    private int LOGO = 1;//状态码，1为正常，2为编辑患者，-1为新增患者

    Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_patient;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        relation = getIntent().getStringExtra("relation");

        text_bd.setVisibility(View.VISIBLE);
        reg_layout.setVisibility(View.VISIBLE);
        mes_layout.setVisibility(View.GONE);

        Log.e("relation","发达省份的"+relation);

    }


    @OnClick({R.id.registered_button,R.id.reg_code_button,R.id.button_jian, R.id.button_jin, R.id.date, R.id.guomin_a, R.id.guomin_b, R.id.bingshi_a, R.id.bingshi_b})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.reg_code_button:

                //判断用户输入是否为空
                if (getAccount().isEmpty()) {
                    Toast("你输入的账号为空！");
                    return;
                }
                if (!isChinaPhoneLegal(getAccount())) {
                    Toast("输入正确的手机号码！");
                    return;
                }

                //拿到正确的手机号
                phone_number = getAccount();


                if(LOGO == -1){
                    getaddCode();
                }else{

                    getCode();

                }


                break;

            case R.id.registered_button:

                //判断用户输入是否为空
                if(LOGO == 1){

                if (getAccount().isEmpty()) {
                    Toast("你输入的账号为空！");
                    return;
                }

                if (!isChinaPhoneLegal(getAccount())) {
                    Toast("输入正确的手机号码！");
                    return;
                }

                if (regCodeEdt.getText().toString().isEmpty()) {
                    Toast("验证码不能为空！");
                    return;
                }

                //拿到正确的手机号
                phone_number = getAccount();
                getAllDoctor();

                }else if(LOGO == 2){

                    //判断输入
                    if (name.getText().toString().trim().equals("")) {
                        Toast("请输入名字");
                    } else if (numbers.getText().toString().trim().equals("")) {
                        Toast("请输入正确的身份证号码");
                    } else if (sex == 0) {
                        Toast("请选择性别");
                    } else if (date.getText().toString().trim().equals("")) {
                        Toast("请输入出生日期");
                    } else if (weight.getText().toString().trim().equals("")) {
                        Toast("请输入重量");
                    } else if (numbers.getText().toString().trim().equals("")) {
                        Toast("请输入正确的身份证号码");
                    } else {

                        addPatient();

                    }

                }else if(LOGO == -1){

                    if (getAccount().isEmpty()) {
                        Toast("你输入的账号为空！");
                        return;
                    }

                    if (!isChinaPhoneLegal(getAccount())) {
                        Toast("输入正确的手机号码！");
                        return;
                    }

                    if (regCodeEdt.getText().toString().isEmpty()) {
                        Toast("验证码不能为空！");
                        return;
                    }
                    //判断输入
                    if (name.getText().toString().trim().equals("")) {
                        Toast("请输入名字");
                    } else if (numbers.getText().toString().trim().equals("")) {
                        Toast("请输入正确的身份证号码");
                    } else if (sex == 0) {
                        Toast("请选择性别");
                    } else if (date.getText().toString().trim().equals("")) {
                        Toast("请输入出生日期");
                    } else if (weight.getText().toString().trim().equals("")) {
                        Toast("请输入重量");
                    } else if (numbers.getText().toString().trim().equals("")) {
                        Toast("请输入正确的身份证号码");
                    } else {

                        patientAdd();

                    }

                }
                break;

            case R.id.button_jian:

                buttonJian.setBackgroundColor(this.getResources().getColor(R.color.main_bg));
                buttonJin.setBackgroundColor(this.getResources().getColor(R.color.button));
                sex = 1;
                break;

            case R.id.button_jin:

                buttonJian.setBackgroundColor(this.getResources().getColor(R.color.button));
                buttonJin.setBackgroundColor(this.getResources().getColor(R.color.main_bg));
                sex = 2;
                break;

            case R.id.date:
                new DatePickerDialog(mActivity, onDateSetListener, mYear, mMonth, mDay).show();
                break;

            case R.id.guomin_a:
                guominA.setBackgroundColor(this.getResources().getColor(R.color.main_bg));
                guominB.setBackgroundColor(this.getResources().getColor(R.color.button));
                guomin.setVisibility(View.GONE);
                gm = false;
                break;

            case R.id.guomin_b:
                guominA.setBackgroundColor(this.getResources().getColor(R.color.button));
                guominB.setBackgroundColor(this.getResources().getColor(R.color.main_bg));
                guomin.setVisibility(View.VISIBLE);
                gm = true;
                break;

            case R.id.bingshi_a:
                bingshiA.setBackgroundColor(this.getResources().getColor(R.color.main_bg));
                bingshiB.setBackgroundColor(this.getResources().getColor(R.color.button));
                bingshi.setVisibility(View.GONE);
                bs = false;
                break;

            case R.id.bingshi_b:
                bingshiA.setBackgroundColor(this.getResources().getColor(R.color.button));
                bingshiB.setBackgroundColor(this.getResources().getColor(R.color.main_bg));
                bingshi.setVisibility(View.VISIBLE);
                bs = true;
                break;

        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:


                    try {

                        Log.e("返回参数","返回参数"+msg.obj.toString());

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());

                        if(jsonObject.getInt("code") == 1){
                            finish();
                        }

                        Toast(jsonObject.getString("msg"));


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        Toast(jsonObject.getString("msg"));

//                      {"code":0,"msg":"手机暂未注册账号","data":false}
                        if(jsonObject.getInt("code") == 0){

                            //页面返回时，弹出提示框，包括确认、取消按钮，提示文字
                            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                            builder.setTitle("该账户未注册患者账号，是否现在注册？");
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.setPositiveButton("注册", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    LOGO = -1;
                                    reg_layout.setVisibility(View.VISIBLE);
                                    text_bd.setVisibility(View.GONE);
                                    mes_layout.setVisibility(View.VISIBLE);
                                    dialog.dismiss();

                                }
                            });
                            builder.show();

                        }else{

                            TimeCount timeCount = new TimeCount(regCodeButton, 60000, 1000);
                            timeCount.start();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast("请联系客服");
                    }
                    break;

                case 3:

                    try {

                        Log.e("fasfasf","返回数据"+msg.obj.toString());

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());

                        int code = jsonObject.getInt("code");

                        if(code == 1){

                            Toast(jsonObject.getString("msg"));
                            finish();

                        }else if(code == 2){

                            LOGO = 2;
                            reg_layout.setVisibility(View.GONE);
                            text_bd.setVisibility(View.GONE);
                            mes_layout.setVisibility(View.VISIBLE);
                            Toast(jsonObject.getString("msg"));

                            Gson gson = new Gson();
                            patient = gson.fromJson(jsonObject.getString("data"),Patient.class);
                            handler.sendEmptyMessage(4);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast("请联系客服");
                    }

                    break;

                case 4:

                    if(patient != null){

                        name.setText(patient.getName());
                        numbers.setText(patient.getIdcard());

                    }

                    break;

                case 5:

                try {

                    JSONObject jsonObject = new JSONObject(msg.obj.toString());

                    if(jsonObject.getInt("code") == 1){
                        finish();
                    }

                    Toast(jsonObject.getString("msg"));


                } catch (JSONException e) {
                    e.printStackTrace();
                }
                    break;

            }

        }
    };


    /**
     * 日期选择器对话框监听
     */
    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String days;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {

                    days = new StringBuffer().append(mYear).append("").append("0").
                            append(mMonth + 1).append("").append("0").append(mDay).toString();

                } else {

                    days = new StringBuffer().append(mYear).append("").append("0").
                            append(mMonth + 1).append("").append(mDay).toString();

                }

            } else {

                if (mDay < 10) {

                    days = new StringBuffer().append(mYear).append("").
                            append(mMonth + 1).append("").append("0").append(mDay).toString();

                } else {

                    days = new StringBuffer().append(mYear).append("").
                            append(mMonth + 1).append("").append(mDay).toString();

                }

            }

            date.setText(days);

        }
    };

    //编辑用户资料
    public void addPatient() {

        List<String> l = new ArrayList<>();
        l.add(date.getText().toString());
        l.add(numbers.getText().toString());
        l.add(patient.getMobile());
        l.add(name.getText().toString());
        l.add(patient.getPatient_id());
        l.add(relation);
        l.add(sex + "");
        l.add(weight.getText().toString());

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "editPatient");

        params.put("data[patient_id]",patient.getPatient_id());
        params.put("data[mobile]",patient.getMobile());
        params.put("data[birthday]",date.getText().toString());
        params.put("data[idcard]", numbers.getText().toString());
        params.put("data[name]", name.getText().toString());
        params.put("data[sex]", sex);
        params.put("data[weight]", weight.getText().toString());
        params.put("data[relation]", relation);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }

    //新增患者
    public void patientAdd() {

        List<String> l = new ArrayList<>();
        l.add(date.getText().toString());
        l.add(regCodeEdt.getText().toString());
        l.add(numbers.getText().toString());
        l.add(phone_number);
        l.add(name.getText().toString());
        l.add(relation);
        l.add(sex + "");
        l.add(weight.getText().toString());

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "patientAdd");

        params.put("data[code]", regCodeEdt.getText().toString());
        params.put("data[birthday]",date.getText().toString());
        params.put("data[idcard]", numbers.getText().toString());
        params.put("data[name]", name.getText().toString());
        params.put("data[sex]", sex);
        params.put("data[weight]", weight.getText().toString());
        params.put("data[relation]", relation);
        params.put("data[mobile]", phone_number);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 5, 404);

    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
     * 166
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 获取手机号
     */
    public String getAccount() {
        return regAccount.getText().toString().trim();//去掉空格
    }

    /**
     * 获取验证码
     */
    public void getCode() {

        //请求网络
        Map<String, Object> params = new HashMap<>();
        params.put("data[mobile]", phone_number);
        params.put("data[type]", "user");
        params.put("data[role]", "1");
        params.put("cmd", "sendsms");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/api/", params, handler, 2, 404);

    }

    public void getaddCode() {

        //请求网络
        Map<String, Object> params = new HashMap<>();
        params.put("data[mobile]", phone_number);
        params.put("data[type]", "add");
        params.put("data[role]", "1");
        params.put("cmd", "sendsms");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/api/", params, handler, 2, 404);

    }

    //绑定患者
    public void getAllDoctor() {

        List<String> l = new ArrayList<>();
        l.add(regCodeEdt.getText().toString());
        l.add(phone_number);
        l.add(relation);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "bindingPatient");
        params.put("data[mobile]", phone_number);
        params.put("data[code]", regCodeEdt.getText().toString());
        params.put("data[relation]", relation);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 3, 404);

    }




}
